package dao

import (
	"web/app/enum"
	"web/app/mode"
	"web/mysql"
	"web/util"
)

var t_user = "users"

type User struct {

}

func (d User) Reg(pUser, pPwd string) error {
	err := mysql.DB.Table(t_user).Create(&mode.User{
		User:  pUser,
		Pwd:   pPwd,
		State: enum.User_State_Yes,
		Time:  util.GetTime(),
	}).Error
	return err
}

func (d User) Login(pUser, pPwd string) (error, *mode.User) {
	err, user := d.Get(&mode.User{
		User: pUser,
		Pwd:  pPwd,
	})
	return err, user
}

func (d User) NewPwd(pUid int, oldPwd, newPwd string) error {
	err := mysql.DB.Table(t_user).Where("uid=? AND pwd=?", pUid, oldPwd).Updates(&mode.User{
		Pwd:    newPwd,
		Uptime: util.GetTime(),
	}).Error
	return err
}

func (d User) Out(pUid int) error {
	err := mysql.DB.Table(t_user).Where("uid=?", pUid).Update("uptime", 0).Error
	return err
}

func (d User) Get(pU *mode.User) (error, *mode.User) {
	var u mode.User
	err := mysql.DB.Table(t_user).Where(pU).Take(&u).Error
	return err, &u
}

func (d User) GetAll(pU *mode.User) (error, *[]mode.User) {
	var u []mode.User
	limit, offset := util.Page(pU.Limit, pU.Page)

	tx := mysql.DB.Table(t_user)
	if len(pU.User) != 0 {
		tx.Where("user LIKE ?", "%"+pU.User+"%")
		pU.User = ""
	}
	err := tx.Where(&pU).Offset(offset).Limit(limit).Select("uid", "user", "state", "time").Find(&u).Error
	return err, &u
}

func (d User) Edit(pU *mode.User) error {
	err := mysql.DB.Table(t_user).Updates(pU).Error
	return err
}

type i_user interface {
	Reg(pUser, pPwd string) error
	Login(pUser, pPwd string) (error, *mode.User)
	NewPwd(pUid int, oldPwd, newPwd string) error
	Out(pUid int) error
	Get(pU *mode.User) (error, *mode.User)
	GetAll(pU *mode.User) (error, *[]mode.User)
	Edit(pU *mode.User) error
}
